package com.iflytek.uoamp.agent.core.agentclient;

import com.iflytek.uoamp.agent.common.constants.CommonConstants;
import com.iflytek.uoamp.agent.core.conf.AgentCoreConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: ClientSocket
 * @Description: netty客户端
 * @author qinanyuan
 * @date 2017年3月22日 下午9:08:47
 */
public class AgentClient{
    private static volatile AgentClient instance;

    private String host;

    private int port;

    private boolean isStart = false;

    private ChannelFuture future;

    private Bootstrap bootstrap;

    private EventLoopGroup workGroup;

    public ChannelFuture getFuture() {
        return future;
    }

    public void setFuture(ChannelFuture future) {
        this.future = future;
    }

    public static AgentClient getInstance() {
        if (instance == null) {
            synchronized (AgentClient.class) {
                if (instance == null) {
                    instance = new AgentClient();
                }
            }
        }
        return instance;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public static void setInstance(AgentClient instance) {
    	AgentClient.instance = instance;
    }

    public void start(String host, int port ) {
        workGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(workGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChildChannelHandler());
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            //端口可配
        isStart = doConnect(host ,port);

        while (!isStart){
            // 10s 之后尝试重新连接服务器
            System.out.println("10s 之后尝试重新连接服务器... isStart = false");
            try {
                TimeUnit.SECONDS.sleep(CommonConstants.CONNECT_INTERVAL);
                isStart = AgentClient.getInstance().doConnect(AgentCoreConfig.getInstance().getHost() ,AgentCoreConfig.getInstance().getPort());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }


    /**
     * 抽取出该方法 (断线重连时使用)
     *
     * @throws InterruptedException
     */
    public boolean doConnect(String host, int port ){
        try{
            future = bootstrap.connect(host, port).sync();
            if (future.isSuccess()){
                setFuture(future);
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }


}
